//
//  MyAttentionViewController.m
//  1gene
//
//  Created by 1jiyin on 16/3/16.
//  Copyright © 2016年 1jiyin. All rights reserved.
//
//*******************我关注的*******************
#import "MyAttentionViewController.h"
#import "MyCareViewController.h"
#import "CommunityChatViewController.h"
#import "CommunityGoodFriendViewController.h"
#import "SelectGroupViewController.h"


#define kCurrentUserToken [[NSUserDefaults standardUserDefaults]objectForKey:@"token"]

@interface MyAttentionViewController ()<MyAttentionTableViewDelegate,UITextViewDelegate>

@property(nonatomic,copy)UIView *reportView;

@property(nonatomic,copy)UITextView *myTextView;

@property (nonatomic, assign) BOOL currentUserIsFriend; // 当前用户是否是好友，张国文写的

@end



@implementation MyAttentionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:[UIView new]];
    self.view.backgroundColor=[UIColor whiteColor];
   // [self createUI];
    [self judgeCurrentISFriend];
    
    // Do any additional setup after loading the view.
}

// 张国文写的，判断当前用户是否是好友
- (void)judgeCurrentISFriend
{
    // 保存当前用户是否是好友
   
    NSString *getFriendListUrl = [NSString stringWithFormat:@"%@?token=%@", kZGWFriendLieBiao, kCurrentUserToken];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:getFriendListUrl parameters:nil
success:^(NSURLSessionDataTask *task, id responseObject) {
    NSInteger result = 1; // 结果为0的话表示是好友，1代表不是好友
    NSInteger tempCount = 0;
    NSArray *friend_groupsArray = [responseObject valueForKey:@"friend_groups"];
    for (NSArray *friend_groupsDic in friend_groupsArray) {
        NSArray *memberArray = [friend_groupsDic valueForKey:@"members"];
        for (NSArray *membersDic in memberArray) {
            if ([[membersDic valueForKey:@"user_id"] isEqualToString:self.userId]) {
                // 说明用户好友列表里面包含有当前用户
                tempCount = 0;
            } else {
                tempCount = 1;
            }
            result = tempCount * result;
        }
    }
    
    if (result == 0) {
        // 说明是好友
        self.currentUserIsFriend = YES;
        NSLog(@"是好友");
    } else if (result == 1) {
        // 说明不是好友
        self.currentUserIsFriend = NO;
        NSLog(@"不是好友");
    }

    [self createUI];
    
} failure:^(NSURLSessionDataTask *task, NSError *error) {
    [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"提示" Content:@"好友列表获取失败" ToView:self];
}];
    
}

-(void)createUI
{
    // 需要加一个无用的leftbar
    UIImageView *llll =[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    llll.image = [UIImage imageNamed:@"houtui"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:llll];
    
    
    self.navigationController.navigationBar.hidden=YES;
    
    if (self.currentUserIsFriend == YES) {
        MyAttentionTableView *table=[[MyAttentionTableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStyleGrouped hideheaderView:NO userId:_userId withIsFriend:YES];
        table.imgDelegate=self;
        [self.view addSubview:table];
    } else if (self.currentUserIsFriend == NO) {
        MyAttentionTableView *table=[[MyAttentionTableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStyleGrouped hideheaderView:NO userId:_userId withIsFriend:NO];
        table.imgDelegate=self;
        [self.view addSubview:table];
    }
    
    
    
    _reportView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [self.view addSubview:_reportView];
    
    
    UIView *reportViewBackgroundView=[[UIView alloc]initWithFrame:_reportView.bounds];
    reportViewBackgroundView.backgroundColor=[UIColor blackColor];
    reportViewBackgroundView.alpha=0.6;
    [_reportView addSubview:reportViewBackgroundView];
    
    UIButton *cancelAllBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    cancelAllBtn.frame=reportViewBackgroundView.bounds;
    [cancelAllBtn addTarget:self action:@selector(cancelAllBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_reportView addSubview:cancelAllBtn];
    
    
    UIView *cellView=[[UIView alloc]initWithFrame:CGRectMake((self.view.frame.size.width-200)/2.0, 100, 200, 250)];
    cellView.backgroundColor=[UIColor whiteColor];
    cellView.layer.borderColor=[UIColor whiteColor].CGColor;
    cellView.layer.borderWidth=1.0;
    cellView.layer.cornerRadius=5.0;
    [_reportView addSubview:cellView];
    
    
    
    UILabel *reasonLab=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 35)];
    reasonLab.text=@"原因";
    //reasonLab.backgroundColor=[UIColor whiteColor];
    reasonLab.textAlignment=NSTextAlignmentCenter;
    reasonLab.font=[UIFont systemFontOfSize:22];
    reasonLab.textColor=[UIColor blackColor];
//    reasonLab.layer.borderColor=[UIColor grayColor].CGColor;
//    reasonLab.layer.borderWidth=1.0;
//    reasonLab.layer.cornerRadius=0;
    [cellView addSubview:reasonLab];
    
    //线
    UIView *line1=[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(reasonLab.frame), 200, 0.5)];
    line1.backgroundColor=[UIColor colorWithRed:235/255.0 green:235/255.0 blue:241/255.0 alpha:1];
    [cellView addSubview:line1];
    
    UITextView *textView=[[UITextView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(line1.frame), reasonLab.frame.size.width, 150)];
    textView.text=@"请填写举报的原因(不少于10个字)";
    textView.font=[UIFont systemFontOfSize:16];
    textView.backgroundColor=[UIColor whiteColor];
    textView.textColor=[UIColor blackColor];
    textView.delegate=self;
//    textView.layer.borderColor=[UIColor grayColor].CGColor;
//    textView.layer.borderWidth=1.0;
//    textView.layer.cornerRadius=5.0;
    _myTextView=textView;
    [cellView addSubview:textView];
    
    //线
    UIView *line2=[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(textView.frame), 200, 0.5)];
    line2.backgroundColor=[UIColor colorWithRed:235/255.0 green:235/255.0 blue:241/255.0 alpha:1];
    [cellView addSubview:line2];
    
    UIButton *cancelBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.frame=CGRectMake(10, CGRectGetMaxY(line2.frame)+10, 80, 35);
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    cancelBtn.backgroundColor=[UIColor colorWithRed:84/255.0 green:199/255.0 blue:222/255.0 alpha:1];
    cancelBtn.layer.borderColor=[UIColor colorWithRed:84/255.0 green:199/255.0 blue:222/255.0 alpha:1].CGColor;
    cancelBtn.layer.borderWidth=2.0;
    cancelBtn.layer.cornerRadius=5.0;
    cancelBtn.titleLabel.font=[UIFont systemFontOfSize:20];
    [cancelBtn addTarget:self action:@selector(cancelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [cellView addSubview:cancelBtn];

    
    
    UIButton *reportBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    reportBtn.frame=CGRectMake(110, CGRectGetMaxY(textView.frame)+10, 80, 35);
    [reportBtn setTitle:@"发送" forState:UIControlStateNormal];
    [reportBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    reportBtn.backgroundColor=[UIColor colorWithRed:84/255.0 green:199/255.0 blue:222/255.0 alpha:1];
    reportBtn.layer.borderColor=[UIColor colorWithRed:84/255.0 green:199/255.0 blue:222/255.0 alpha:1].CGColor;
    reportBtn.layer.borderWidth=2.0;
    reportBtn.layer.cornerRadius=5.0;
    reportBtn.titleLabel.font=[UIFont systemFontOfSize:20];
    [reportBtn addTarget:self action:@selector(reportBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [cellView addSubview:reportBtn];
    
    _reportView.hidden=YES;
    
}
//发送举报
-(void)reportBtnClick:(UIButton *)sender
{
    if ([_myTextView.text isEqualToString:@"请填写举报的原因(不少于10个字)"]||_myTextView.text.length==0) {
        _reportView.hidden=YES;
        [self.view showTiShiMessage:@"内容不能为空"];
        return;
    }else if (_myTextView.text.length<=10)
    {
        _reportView.hidden=YES;
        [self.view showTiShiMessage:@"最少10个字"];
        return;
    }
    else{
        [self reportUser];
    }
    [self.navigationController.view endEditing:YES];
}

//取消
-(void)cancelBtnClick:(UIButton *)sender
{
    _reportView.hidden=YES;
    [self.navigationController.view endEditing:YES];
}

//点击空白取消举报
-(void)cancelAllBtnClick:(UIButton *)sender
{
    _reportView.hidden=YES;
    [self.navigationController.view endEditing:YES];
}

//更多
-(void)moreSelectedIndex:(NSInteger)index
{
    if (index == 1) {
        //举报
    }else if (index == 2)
    {
        //发消息
    }else if (index  == 3)
    {
        //删除
        NSLog(@"删除好友");
        [self addDeleteFriendAlert];
        
    }else if (index == 4)
    {
        //分组
        NSLog(@"分组");
        SelectGroupViewController *selectGroupVC = [[SelectGroupViewController alloc] init];
      //  selectGroupVC.fenZuMingZiArray = [NSMutableArray arrayWithArray:self.fenZuNameArray];
      //  selectGroupVC.selectedGroupName = self.userIdOnGroupName;
        selectGroupVC.shouldShowFinishButton = YES;
        selectGroupVC.friend_id = self.userId;
        selectGroupVC.shouldGetFenZuData = YES;
       // selectGroupVC.fenZuMingZiDuiYingIDDic = [NSMutableDictionary dictionaryWithDictionary:self.fenZuNameDuiYingIDDic];
        selectGroupVC.selectGroupBlock = ^void(NSString *string) {
            
        };
        [self.navigationController pushViewController:selectGroupVC animated:YES];
        
    }else{
        [self.view showTiShiMessage:@"服务器繁忙,请稍后再试"];
    }
}



//代理
-(void)startReport
{
    
    _reportView.hidden=NO;
    _reportView.alpha=0;
    [UIView animateWithDuration:0.6 animations:^{
        _reportView.alpha=1;
    }];
    
}

//举报
-(void)reportUser
{
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *token=[user objectForKey:@"token"];

    NSDictionary *params=@{@"informed_user_id":_userId,@"reason":_myTextView.text};
    
        [manager POST:[NSString stringWithFormat:ReportUser,token] parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"举报%@",dic);
            _reportView.hidden=YES;
            [self.view showTiShiMessage:@"举报成功"];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error%@",error.localizedDescription);
             _reportView.hidden=YES;
            [self.view showTiShiMessage:@"举报失败"];
        }];
}

//textViewa的代理
-(void)textViewDidBeginEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:@"请填写举报的原因(不少于10个字)"]) {
        textView.text=nil;
    }
}

-(void)textViewDidEndEditing:(UITextView *)textView
{
    if (textView.text.length==0) {
        textView.text=@"请填写举报的原因(不少于10个字)";
    }
}




//TieBaTableView的代理
-(void)bigImage:(NSInteger)currentIndex AndImageArrays:(NSArray *)imageArrays
{
    CommunityBigImageViewController *vc=[[CommunityBigImageViewController alloc]init];
    // vc.image=img;
    vc.navigationBarState=1;
    vc.imageArrays=[NSArray arrayWithArray:imageArrays];
    vc.currentIndex=currentIndex;
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)gotoXiangQingViewController:(NSString *)topicId
{
    TieBaXiangQingViewController *vc=[[TieBaXiangQingViewController alloc]init];
    //vc.arr=arr;
    vc.backState=1;
    vc.topic_id=[topicId integerValue];
    self.navigationController.navigationBar.hidden=NO;
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)chooseFunction:(NSInteger)index
{
    //1+关注
    if (index==1) {
        
    }
    //2+好友
    else if (index==2){
        
    }
    //3更多
    else if (index==3){
         
    }
    //4她关注的
   else if (index==4) {
       MyCareViewController *vc=[[MyCareViewController alloc]init];
       vc.userId=_userId;
       vc.myTitle=@"她关注的";
       [self.navigationController pushViewController:vc animated:YES];
    }
    //5她的好友
   else if (index==5){
       CommunityGoodFriendViewController *vc=[[CommunityGoodFriendViewController alloc]init];
       vc.myTitle=@"她的好友";
       [self.navigationController pushViewController:vc animated:YES];
   }
    //6她的粉丝
   else if (index==6){
       NSLog(@"当前用户的id=====%@",_userId);
       FanpageViewController *vc=[[FanpageViewController alloc]init];
       vc.userId=_userId;
       [self.navigationController pushViewController:vc animated:YES];
   }
    //7她的收藏
   else if (index==7){
       MyCollectionViewController *vc=[[MyCollectionViewController alloc]init];
       vc.barState=2;
       vc.userId=_userId;
       NSLog(@"得到的userId====%@",_userId);
       [self.navigationController pushViewController:vc animated:YES];
   }
    
    
}
//返回上一页
-(void)gotoUpViewController
{
    if (_barState==1) {
        //self.navigationController.navigationBar.hidden=NO;
        self.navigationController.navigationBar.hidden=NO;
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        self.navigationController.navigationBar.hidden=YES;
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}
//进入我关注的界面
-(void)gotoMyAttentionViewController
{
    
}
//点击用户头像响应
-(void)userHeadClick
{
    
}


//更多标签按钮点击事件
-(void)moreBiaoQianBtnClick:(NSMutableArray *)arr
{
    BiaoQianViewController *vc=[[BiaoQianViewController alloc]init];
    vc.myTabBarState=1;
    vc.allBiaoQianArray=[NSMutableArray arrayWithArray:arr];
    self.navigationController.navigationBar.hidden=NO;
    [self.navigationController pushViewController:vc animated:YES];
}



//个性签名完整显示
-(void)allPersonalNameBtnClick:name
{
    PersonalNameViewController *vc=[[PersonalNameViewController alloc]init];
    vc.personalName=name;
    vc.myTabBarState=1;
    self.navigationController.navigationBar.hidden=NO;
    self.tabBarController.tabBar.hidden=YES;
    [self.navigationController pushViewController:vc animated:YES];
}
//发消息
-(void)startChat:(NSString *)userId
{
    //新建一个聊天会话View Controller对象
    CommunityChatViewController *chat = [[CommunityChatViewController alloc]init];
    //设置会话的类型为聊天室
    chat.conversationType = ConversationType_PRIVATE;
    //设置会话的目标会话ID
    chat.targetId = userId;
    //设置聊天会话界面要显示的标题
    chat.title = @"会话";
    //设置加入聊天室时需要获取的历史消息数量，最大值为50
    chat.defaultHistoryMessageCountOfChatRoom = 20;
    //显示聊天会话界面
    self.tabBarController.tabBar.hidden=YES;
    [self.navigationController pushViewController:chat animated:YES];
}

-(void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden=YES;
    self.navigationController.navigationBar.hidden=YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
}

#pragma mark - 删除好友的提醒框
- (void)addDeleteFriendAlert
{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"警告" message:@"您确定删除该好友么" preferredStyle:UIAlertControllerStyleAlert];
    // 修改标题颜色
    NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:@"警告"];
    [title addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 2)];
    [title addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(0, 2)];
    [alertVC setValue:title forKey:@"attributedTitle"];
    
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] startAnimation];
       // 删除好友的url
        NSString *deleteFriendUrl = [NSString stringWithFormat:@"%@?token=%@", kZGWDeleteFriendUrl, kCurrentUserToken];
        NSDictionary *paramaterDic = @{@"friend_id":self.userId};
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager DELETE:deleteFriendUrl parameters:paramaterDic success:^(NSURLSessionDataTask *task, id responseObject) {
            NSDictionary *status = [responseObject valueForKey:@"status"];
            NSString *msgString = [status valueForKey:@"msg"];
            if ([msgString isEqualToString:@"delete success"]) {
                // 删除成功
                [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertNoTitieWithContent:@"删除成功" toView:self];
                // 设置需要联系人界面刷新
                [[NetStatusHandle shareHandle] setShouldFreshOnLianXiRen:@"YES"];
            }
            [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
            [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"提示" Content:@"删除失败，请重试" ToView:self];
        }];
        
    }];
    [alertVC addAction:sureAction];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertVC addAction:cancelAction];
    [self presentViewController:alertVC animated:YES completion:nil];

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
